package it.asvp.asvp_portal.data.dao.impl;


import it.asvp.asvp_portal.data.dao.FileDao;
import it.asvp.asvp_portal.data.entity.domain.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class FileDaoImpl implements FileDao{

	private static final Log log = LogFactory.getLog(FileDaoImpl.class);

	@Autowired
	SessionFactory sessionFactory;

	public Long persist(File transientInstance) {
		log.debug("persisting File instance");
		Long id;
		try {
			id=(Long) sessionFactory.getCurrentSession().save(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
		return id;
	}


	public void delete(File persistentInstance) {
		log.debug("deleting File instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public File merge(File detachedInstance) {
		log.debug("merging File instance");
		try {
			File result = (File) sessionFactory.getCurrentSession().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public File findById(java.lang.Long id) {
		log.debug("getting File instance with id: " + id);
		try {
			
			Criteria cr=sessionFactory.getCurrentSession().createCriteria(File.class);
			cr.add(Restrictions.eq("id", id));
			File file = (File)cr.uniqueResult();
			
			log.debug("findById eseguito con successo");
			
			if (file == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return file;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

}
